﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdoWZQ
{
    class DataBaseHelper
    {
        private readonly string sqlCommandString = "select * from student";

        private readonly string connnectionString = "server=.;database=Krystal;uid=sa;pwd=wzq0307";


        public static void PrintUserInfo()
        {
            string connnectionString = "server=.;database=Krystal;uid=sa;pwd=wzq0307";   // .是指当前数据库服务器；database--数据库名；uid--用户名；pwd--密码

            SqlConnection sqlConnection = new SqlConnection(connnectionString);    //连接，定义一个connection；构造函数是一种方法、函数，会特意用来创造、实例化对象的方法

            sqlConnection.Open();    //Open就是打开到当前数据库的连接

            var SqlCommandString = "select * from student";   //查询单独拿出来，变成变量

            SqlCommand sqlCommand = new SqlCommand(SqlCommandString, sqlConnection);

            //或者 SqlCommand sqlCommand = new SqlCommand("select * from student",sqlConnection);

            var sdr = sqlCommand.ExecuteReader();   //只读的流

            Console.WriteLine("{0}\t{1}\t{2}", "编号", "学生姓名", "班级编号");

            while (sdr.Read())
            {

                Console.WriteLine("{0}\t{1}\t{2}", sdr["studentId"], sdr["studentName"], sdr["classId"]);

            }

            sqlConnection.Close();

        }
        //ado第一次作业<获取表数据>（法二）
        public void PrintUserInfoAdaper()
        {

            SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommandString, connnectionString);  //SqlDataAdapter——类型 ；dataAdapter——命令 ； sqlCommandString、connnectionString——连接字符串

            DataTable dataTable = new DataTable();

            dataAdapter.Fill(dataTable);   //此作业中的dataTable可将其理解成一张表
            Console.WriteLine();

            Console.WriteLine();

            Console.WriteLine();

            Console.WriteLine();

            Console.WriteLine("{0}\t{1}\t{2}", "编号", "学生姓名", "班级编号");

            for (int i = 0; i < dataTable.Rows.Count; i++)
            {

                Console.WriteLine("{0}\t{1}\t{2}", dataTable.Rows[i]["studentId"], dataTable.Rows[i]["studentName"], dataTable.Rows[i]["classId"]);

            }
        }
    }
}
